package com.padakeji.android.pworks.content;


import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.lang.reflect.Type;

/**
 * Created by atanl on 2015/11/10.
 */
public class SharedPreferencesHelper {

    private String spName = "pWorks.SP.Helper";
    private SharedPreferences sp;

    private Context mContext;
    private JsonWorker jsonWorker;

    public SharedPreferencesHelper(Context context) {
        mContext = context;
        sp = mContext.getSharedPreferences(spName, Context.MODE_PRIVATE);
        jsonWorker = JsonWorkerFactory.getJsonWorker();
    }

    public void save(@NonNull String key, @NonNull Object o) {
        ValueDescriptor vd = new ValueDescriptor();
        String json = jsonWorker.toJson(o);
        vd.valueJson = json;
        vd.typeName = o.getClass().getName();

        String toSave = jsonWorker.toJson(vd);
        sp.edit().putString(key, toSave).commit();
    }

    public <T> T get(@NonNull String key) {
        if (key == null) {
            return null;
        }
        String v = sp.getString(key, null);
        if (v != null) {
            ValueDescriptor vd = jsonWorker.fromJson(v, ValueDescriptor.class);
            try {
                return jsonWorker.fromJson(vd.valueJson, (Type) Class.forName(vd.typeName));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public void remove(@NonNull String key) {
        if (TextUtils.isEmpty(key)) {
            return;
        }
        sp.edit().remove(key).commit();
    }

    private static class ValueDescriptor {
        public String valueJson;
        public String typeName;
    }

}
